<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入姓名或手机号"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAddEmployee"
            >新增员工</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="employeeList"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          align="center"
          label="姓名"
          prop="name"
        ></el-table-column>
        <el-table-column
          align="center"
          label="性别"
          prop="gender"
          width="100"
        ></el-table-column>
        <el-table-column
          align="center"
          label="手机号码"
          prop="telephone"
        ></el-table-column>
        <el-table-column
          align="center"
          label="身份证号"
          prop="id_card"
        ></el-table-column>
        <el-table-column
          align="center"
          label="职务"
          width="150"
          prop="job_name"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getEmployees"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑员工' : '新增员工'"
      width="30%"
    >
      <el-form
        :model="employeeForm"
        :rules="employeeFormRules"
        ref="employeeFormRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            type="text"
            v-model="employeeForm.name"
            placeholder="姓名"
            maxlength="24"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="employeeForm.gender"
            placeholder="请选择性别"
            clearable
          >
            <el-option
              v-for="item in genders"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="telephone">
          <el-input
            v-model="employeeForm.telephone"
            placeholder="手机号码"
            clearable
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input
            v-model="employeeForm.id_card"
            maxlength="18"
            show-word-limit
            placeholder="身份证号"
            clearable
          />
        </el-form-item>
        <el-form-item label="职务" prop="job">
          <el-select
            v-model="employeeForm.job"
            placeholder="选择职务"
            clearable
          >
            <el-option
              v-for="item in jobs"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="SaveEmployee">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getEmployees,
  addEmployee,
  updateEmployee,
  delEmployee,
} from "@/api/employee";
import { getJobs } from "@/api/job";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: undefined,
  name: "",
  gender: "",
  telephone: "",
  id_card: "",
  job: undefined,
  job_name: "",
};

export default {
  name: "Empolyee",
  data() {
    // 验证手机号的规则
    const checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };

    return {
      employeeForm: Object.assign({}, defaultForm),
      employeeFormRules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 1,
            max: 24,
            message: "长度在 1 到 30 个字符",
            trigger: "blur",
          },
        ],
        telephone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      jobs: [],
      genders: [
        {
          value: "男",
          label: "男",
        },
        {
          value: "女",
          label: "女",
        },
      ],
      dialogVisible: false,
      dialogType: "new",
      employeeList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        name: undefined,
      },
    };
  },
  components: {
    Pagination,
  },
  created() {
    this.getEmployees();
    this.getJobs();
  },
  methods: {
    // 员工列表
    getEmployees() {
      this.listLoading = true;
      getEmployees(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.employeeList = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取员工数据失败");
          this.listLoading = false;
        });
    },
    // 职务列表
    getJobs() {
      getJobs()
        .then((res) => {
          console.log(res);
          this.jobs = res;
        })
        .catch((error) => {
          this.$message.error("获取职务数据失败");
        });
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getEmployees();
    },
    // 增加员工
    handleAddEmployee() {
      this.employeeForm = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.employeeFormRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.employeeForm = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["employeeFormRef"].clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该员工吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delEmployee(row.id);

          this.employeeList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("员工信息删除失败!");
        });
    },
    // 保存操作
    async SaveEmployee() {
      this.$refs.employeeFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        if (isEdit) {
          const res = await updateEmployee(this.employeeForm);
          console.log(isEdit, res);
          const index = this.employeeList.findIndex((v) => v.id === res.id);
          this.employeeList.splice(index, 1, res);
        } else {
          const res = await addEmployee(this.employeeForm);
          const { id } = res;
          if (id > 0) {
            this.getEmployees();
          }
        }

        const { name, telephone, id_card } = this.employeeForm;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>姓名: ${name}</div>
              <div>手机号: ${telephone}</div>
              <div>身份证: ${id_card}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  // .box-card{
  //   margin-top: 30px;
  // }
  .el-table {
    margin-top: 10px;
    width: 100%;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .el-select {
    width: 100%;
  }
}
</style>